package il.ac.braude.sona.gui.infogui;


/* ===========================================================
 * JFreeChart : a free chart library for the Java(tm) platform
 * ===========================================================
 *
 * (C) Copyright 2000-2004, by Object Refinery Limited and Contributors.
 *
 * Project Info:  http://www.jfree.org/jfreechart/index.html
 *
 * This library is free software; you can redistribute it and/or modify it under the terms
 * of the GNU Lesser General Public License as published by the Free Software Foundation;
 * either version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this
 * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc. 
 * in the United States and other countries.]
 *
 * -----------------------
 * OverlaidXYPlotDemo.java
 * -----------------------
 * (C) Copyright 2002-2004, by Object Refinery Limited.
 *
 * Original Author:  David Gilbert (for Object Refinery Limited).
 * Contributor(s):   -;
 *
 * $Id: OverlaidXYPlotDemo.java,v 1.28 2004/06/02 09:48:24 mungady Exp $
 *
 * Changes
 * -------
 * 28-Mar-2002 : Version 1 (DG);
 * 23-Apr-2002 : Modified to use new OverlaidXYPlot class (DG);
 * 31-May-2002 : Changed plot background color to yellow, to check that it works (DG);
 * 13-Jun-2002 : Renamed OverlaidPlotDemo-->OverlaidXYPlotDemo (DG);
 * 25-Jun-2002 : Removed unnecessary imports (DG);
 * 11-Oct-2002 : Fixed errors reported by Checkstyle (DG);
 *
 */


import il.ac.braude.sona.constants.Statistics;
import il.ac.braude.sona.gui.SONAFrame;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Toolkit;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Map.Entry;

import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.DatasetRenderingOrder;
import org.jfree.chart.plot.IntervalMarker;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYBarRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.function.Function2D;
import org.jfree.data.function.NormalDistributionFunction2D;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.time.Day;
import org.jfree.data.time.SimpleTimePeriod;
import org.jfree.data.time.TimePeriodValues;
import org.jfree.data.time.TimePeriodValuesCollection;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.Layer;
import org.jfree.ui.RectangleAnchor;
import org.jfree.ui.RefineryUtilities;
import org.jfree.ui.TextAnchor;

/**
 * A demonstration application showing a time series chart overlaid with a vertical XY bar chart.
 */
public class PeriodicReportFrame extends SONAFrame {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public Statistics stac_active;
	public Statistics stac_suspend;
	public HashMap<String,String> activeResults ;
	public HashMap<String,String> suspendedResults ;
	private HashMap<String,String> executedResults ;
	private HashMap<String,String> rejectedResults ;


	/**
     * Constructs a new demonstration application.
     * @param reportAnswer 
     *
     * @param title  the frame title.
     */
    public PeriodicReportFrame(HashMap<String, HashMap<String, String>> reportAnswer, final String title) {

        super();
        final JFreeChart chart = createOverlaidChart1(reportAnswer);
        final ChartPanel panel = new ChartPanel(chart, true, true, true, true, true);
        final JFreeChart chart2 = createOverlaidChart2(reportAnswer);
        final ChartPanel panel2 = new ChartPanel(chart2, true, true, true, true, true);
		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		panel2.setPreferredSize(new Dimension((dim.width-40)/2,dim.height-140));
       	panel.setPreferredSize(new Dimension((dim.width-40)/2,dim.height-140));
        add(panel,BorderLayout.WEST);
        add(panel2,BorderLayout.EAST);
    }

    /**
     * Creates an overlaid chart.
     * @param reportAnswer 
     *
     * @return The chart.
     */
    private JFreeChart createOverlaidChart1(HashMap<String, HashMap<String, String>> reportAnswer) {

    	int i = 0;
    	double[] active = new double[reportAnswer.get("Active").size()];
    	double[] suspend = new double[reportAnswer.get("Suspended").size()];

    	activeResults = new HashMap<String,String>(reportAnswer.get("Active"));
    	Set<Entry<String, String>> reportData = activeResults.entrySet();
		Iterator<Entry<String, String>> mapitarator = reportData.iterator(); 

		while (mapitarator.hasNext())
		{
			Entry<String, String> map = mapitarator.next();
    	    active[i++] = Double.parseDouble(map.getValue()); 
    	}
		i = 0;
		
		suspendedResults = new HashMap<String,String>(reportAnswer.get("Suspended"));
    	reportData = suspendedResults.entrySet();
		mapitarator = reportData.iterator(); 
		
		while (mapitarator.hasNext())
		{
			Entry<String, String> map = mapitarator.next();
    	    suspend[i++] = Double.parseDouble(map.getValue()); 
    	}
		i = 0;
		double temp = 0;
		for (double b:active)
			temp += b;
		
		stac_active = new Statistics(active);
		temp = temp/stac_active.size;
		System.out.println("size = "+stac_active.size+" mean = "+stac_active.getMean()+" std = "+stac_active.getStdDev()+" my mean = "+temp);
		stac_suspend = new Statistics(suspend);

		
        final IntervalXYDataset data1 = createDataset1(reportAnswer.get("Active"),"Active Requests");
        final IntervalXYDataset data2 = createDataset1(reportAnswer.get("Suspended"),"Suspended Requests");


        final XYItemRenderer renderer1 = new XYBarRenderer(0.20);
        final ValueAxis rangeAxis = new NumberAxis("Num Of Requests");
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        rangeAxis.setAutoTickUnitSelection(false);
        final XYPlot subplot1 = new XYPlot(data1, null, rangeAxis, renderer1); 
        subplot1.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
        
        final XYItemRenderer renderer2 = new XYBarRenderer(0.20);
        final ValueAxis rangeAxis2 = new NumberAxis("Num Of Requests");
        rangeAxis2.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        final XYPlot subplot2 = new XYPlot(data2, null, rangeAxis2, renderer2);
        subplot2.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);

    
        final DateAxis domainAxis6 = new DateAxis("Date");
        domainAxis6.setVerticalTickLabels(true);
        domainAxis6.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));
        domainAxis6.setLowerMargin(0.01);
        domainAxis6.setUpperMargin(0.01);
        final CombinedDomainXYPlot plot = new CombinedDomainXYPlot(domainAxis6);
       
        subplot1.addRangeMarker(getIntervalMarker(stac_active), Layer.FOREGROUND);

        subplot2.addRangeMarker(getIntervalMarker(stac_suspend), Layer.FOREGROUND);
        
        plot.add(subplot1, 1);
        plot.add(subplot2, 1);
       

        plot.setOrientation(PlotOrientation.VERTICAL);
        // return a new chart containing the  plot...
        return new JFreeChart("Active & Suspended", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    }


    
    private JFreeChart createOverlaidChart2(HashMap<String, HashMap<String, String>> reportAnswer) {

    	int i = 0;
    	double[] exec = new double[reportAnswer.get("Executed").size()];
    	double[] rejected = new double[reportAnswer.get("Rejected").size()];
    	
    	executedResults = new HashMap<String,String>(reportAnswer.get("Executed"));
    	Set<Entry<String, String>> reportData = executedResults.entrySet();
		Iterator<Entry<String, String>> mapitarator = reportData.iterator();
		
			while (mapitarator.hasNext())
			{
				Entry<String, String> map = mapitarator.next();
	    	    exec[i++] = Double.parseDouble(map.getValue()); 
	    	}
		i = 0;
		rejectedResults = new HashMap<String,String>(reportAnswer.get("Rejected"));
    	reportData = rejectedResults.entrySet();
		mapitarator = reportData.iterator(); 
		
		while (mapitarator.hasNext())
		{
			Entry<String, String> map = mapitarator.next();
    	    rejected[i++] = Double.parseDouble(map.getValue()); 
    	}
		Statistics stac_exec = new Statistics(exec);
		Statistics stac_rejected = new Statistics(rejected);
		
        final IntervalXYDataset data3 = createDataset1(reportAnswer.get("Executed"),"Executed Requests");
        final IntervalXYDataset data4 = createDataset1(reportAnswer.get("Rejected"),"Rejected Requests");
        final GradientPaint gp1 = new GradientPaint(
                0.0f, 0.0f, Color.gray, 
                0.0f, 0.0f, Color.lightGray
            );
            final GradientPaint gp2 = new GradientPaint(
                0.0f, 0.0f, Color.green, 
                0.0f, 0.0f, Color.lightGray
            );
       
        final XYItemRenderer renderer3 = new XYBarRenderer(0.20);
        final DateAxis domainAxis3 = new DateAxis("Dates");
        renderer3.setSeriesPaint(0, gp1);
        final ValueAxis rangeAxis3 = new NumberAxis("Num Of Requests");
        rangeAxis3.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        final XYPlot subplot3 = new XYPlot(data3, domainAxis3, rangeAxis3, renderer3);
        subplot3.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
        
        
        
        final XYItemRenderer renderer4 = new XYBarRenderer(0.20);
        renderer4.setSeriesPaint(0, gp2);
        final DateAxis domainAxis4 = new DateAxis("Dates");
        final ValueAxis rangeAxis4 = new NumberAxis("Num Of Requests");
        rangeAxis4.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        final XYPlot subplot4 = new XYPlot(data4, domainAxis4, rangeAxis4, renderer4);
        subplot4.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
        
  
        
        final DateAxis domainAxis6 = new DateAxis("Date");
        domainAxis6.setVerticalTickLabels(true);
        domainAxis6.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));
        domainAxis6.setLowerMargin(0.01);
        domainAxis6.setUpperMargin(0.01);
        
        
        final CombinedDomainXYPlot plot = new CombinedDomainXYPlot(domainAxis6);
     
        subplot3.addRangeMarker(getIntervalMarker(stac_exec), Layer.FOREGROUND);
        subplot4.addRangeMarker(getIntervalMarker(stac_rejected), Layer.FOREGROUND);

        plot.add(subplot3, 1);
        plot.add(subplot4, 1);
       
        
        plot.setOrientation(PlotOrientation.VERTICAL);

        // return a new chart containing the  plot...
        return new JFreeChart("Executed & Rejected", JFreeChart.DEFAULT_TITLE_FONT, plot, true);

    }

    /**
     * Creates a sample dataset.
     * @param hashMap 
     *
     * @return The dataset.
     */
    @SuppressWarnings({  "static-access" })
	private IntervalXYDataset createDataset1(HashMap<String, String> hashMap,String ser) {

        // create dataset 1...
    	TimePeriodValues series1= new TimePeriodValues(ser);
        Set<Entry<String, String>> reportData = hashMap.entrySet();
		Iterator<Entry<String, String>> mapitarator = reportData.iterator();

		Day day = new Day();
		while (mapitarator.hasNext())
		{
				try {
						Entry<String, String> map = mapitarator.next();
						day=day.parseDay(map.getKey());
						series1.add(new SimpleTimePeriod(day.getStart(),day.getEnd()),Double.parseDouble(map.getValue()));
		
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}

        final TimePeriodValuesCollection dataset = new TimePeriodValuesCollection();
        dataset.addSeries(series1);
        return dataset;

    }

    // ****************************************************************************
    // * JFREECHART DEVELOPER GUIDE                                               *
    // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
    // * to purchase from Object Refinery Limited:                                *
    // *                                                                          *
    // * http://www.object-refinery.com/jfreechart/guide.html                     *
    // *                                                                          *
    // * Sales are used to provide funding for the JFreeChart project - please    * 
    // * support us so that we can continue developing free software.             *
    // ****************************************************************************
    
    /**
     * Creates a sample dataset.
     * @param stac_rejected 
     *
     * @return The dataset.
     */
    
    private IntervalMarker getIntervalMarker(Statistics statics){
        IntervalMarker target = new IntervalMarker(statics.getMean()-statics.getStdDev(), statics.getMean()+statics.getStdDev());
        target.setLabel("Mean="+new DecimalFormat("##.##").format(statics.getMean())+
        		", Stdev="+new DecimalFormat("##.##").format(statics.getStdDev())+
        		", Median="+new DecimalFormat("##.##").format(statics.median()));
        target.setLabelFont(new Font("SansSerif", Font.BOLD,17));
        target.setLabelPaint(Color.black);
        target.setLabelAnchor(RectangleAnchor.LEFT);
        target.setLabelTextAnchor(TextAnchor.CENTER_LEFT);
        target.setPaint(new Color(222, 222, 255, 90));
        return target;
    }
 
 

}